# coding: utf-8

import xlrd
import time
from datetime import datetime, timedelta, date

from flask import (
    render_template, flash, redirect, url_for
)
from flask_login import login_required, current_user

from app.ccws.constant import CallReason
from app.ccws.models import OutBoundRecord
from app.op.constant import MAX_ROW_COUNT, AreaType, UserType, Mastery, \
    ParticStatus, TemplateLength
from app.op.user_schemas import ImportUserSchema, UpdateUserSchema
from . import op_bp
from .models import User, UserTag, Area, Demand, Partic
from .user_forms import ImportUserForm


@op_bp.route('/import/update/users', methods=['GET', 'POST'])
@login_required
def import_update_users():
    """
    create by ld_wu 2017-10-24
    导入更新添加微信好友状态
    :return:
    """
    form = ImportUserForm()

    if form.validate_on_submit():
        book = xlrd.open_workbook(file_contents=form.files.data.stream.read())
        sheet = book.sheet_by_index(0)
        mobile_map = dict()
        error_msg = list()
        if sheet.ncols != TemplateLength.USER_UPDATE:
            flash('模板错误，请检查导入的excel文件！')
            return redirect(url_for('op_bp.import_update_users'))
        if sheet.nrows <= MAX_ROW_COUNT:
            for row in range(1, sheet.nrows):
                row_num = row + 1
                schema = UpdateUserSchema(sheet, row)
                mobile = schema.mobile
                # 若文件中有重复手机号, 则提示
                if mobile in mobile_map:
                    error_msg.append(
                        (row_num, '该电话工程商在文件已存在, 请检查文件')
                    )
                    continue

                mobile_map[mobile] = row_num

                if schema.error_msg:
                    error_msg.extend(schema.error_msg)
                    continue

            if error_msg:
                error_msg = sorted(error_msg, key=lambda x: x[0])
            else:
                users = User.query.filter(
                    User.mobile.in_(
                        filter(lambda x: x, mobile_map.keys())
                    ),
                    User.deleted_at == 0,
                    User.bind_user_id.__eq__(None)
                ).all()
                for user in users:
                    user.bind_user_id = current_user.id
                    user.bind_user_name = current_user.nickname
                    user.bind_date = date.today()
                flash('本次更新{}条！'.format(len(users)))
        else:
            flash(
                '上传数据不可超过{}行，若数据过多请分多次上传！'.format(MAX_ROW_COUNT)
            )
        return render_template(
            'user/update_user_import.html',
            form=form,
            error_msg=error_msg
        )

    return render_template(
        'user/update_user_import.html',
        form=form
    )


@op_bp.route('/import/users/<int:demand_id>', methods=['GET', 'POST'])
@login_required
def import_users(demand_id):
    """
    create by ld_wu 2017-10-24
    导入拉新客户
    :param demand_id:
    :return:
    """

    demand = Demand.get_by_id(demand_id)
    if not demand or not demand.is_ongoing:
        flash('项目必须在进行中')
        return redirect(url_for('op_bp.demand_list'))

    if OutBoundRecord.has_invite_record(current_user.id):
        flash('还有待处理的拉新外呼，请先处理完再重新导入！')
        return redirect(url_for('op_bp.import_users', demand_id=demand_id))

    form = ImportUserForm()

    if form.validate_on_submit():
        book = xlrd.open_workbook(file_contents=form.files.data.stream.read())
        sheet = book.sheet_by_index(0)
        mobile_map = dict()
        error_msg = list()
        data_list = list()
        if sheet.ncols != TemplateLength.USER:
            flash('模板错误，请检查导入的excel文件！')
            return redirect(url_for('op_bp.import_users', demand_id=demand_id))
        if sheet.nrows <= MAX_ROW_COUNT:
            for row in range(1, sheet.nrows):
                row_num = row + 1
                schema = ImportUserSchema(sheet, row)
                mobile = schema.mobile = schema.mobile.replace('-', '')
                # 若文件中有重复手机号则忽略后面的数据，只写入第一条
                if mobile in mobile_map:
                    continue

                mobile_map[mobile] = row_num

                if schema.error_msg:
                    error_msg.extend(schema.error_msg)
                    continue

                data_list.append(schema)

            users = User.query.filter(
                User.mobile.in_(
                    filter(lambda x: x, mobile_map.keys())
                ),
                User.deleted_at == 0
            )
            existed_users = {user.mobile: user for user in users}
            if error_msg:
                error_msg = sorted(error_msg, key=lambda x: x[0])
            else:
                time_stamp = int(time.time())
                # 外呼延迟一年
                delay_call_time = datetime.now() + timedelta(days=365)
                today = date.today()
                for each in data_list:
                    if each.mobile in existed_users:
                        user = existed_users[each.mobile]
                        user_tag = UserTag.default_tag(user.id)
                        if user.type == UserType.CLIENT.value:
                            user.type = UserType.POTENTIAL.value
                        # 本行业并且从未绑定过微信
                        if (user_tag.mastery != Mastery.LAYMAN.value and
                                not user.bind_wx_openid):
                            OutBoundRecord.make_invite_record(
                                user, each.mobile, current_user.id, demand_id
                            )
                    else:
                        para = each.to_dict()
                        city = Area.query.filter(
                            Area.type == AreaType.CITY.value,
                            Area.name.like('%{}%'.format(each.city))
                        ).first()
                        if city:
                            para['city'] = city.name
                            para['area_id'] = city.id

                        prov = Area.query.filter(
                            Area.type == AreaType.PROV.value,
                            Area.name.like('%{}%'.format(each.prov))
                        ).first()
                        if prov:
                            para['prov'] = prov.name
                        user = User.create(
                            industry=2,
                            wx_openid='',
                            remark='{}导入'.format(today),
                            type=UserType.POTENTIAL.value,
                            level=10,  # 新用户默认为铁牌
                            gender=1,  # 性别默认为男
                            status=0,  # 审核状态默认未认证
                            active=1,  # 默认激活?
                            **para
                        )
                        UserTag.default_tag(user.id)
                        OutBoundRecord.create(
                            user_id=user.id,
                            mobile=each.mobile,
                            local_call_id='{}{}'.format(time_stamp, each.mobile),
                            call_reason=CallReason.INVITE_NEW_USER.value,
                            call_weight=1000,
                            schedule_time=delay_call_time,
                            creator_id=current_user.id,
                            demand_id=demand_id
                        )
                        # 潜在工程商直接享有关联项目的信息
                        Partic.create(
                            demand_id=demand.id,
                            supplier_id=user.id,
                            status=ParticStatus.SUCCEED.value,
                            is_revert=True
                        )
                flash('导入成功！')
        else:
            flash(
                '上传数据不可超过{}行，若数据过多请分多次上传！'.format(MAX_ROW_COUNT)
            )
        return render_template(
            'user/user_import.html',
            form=form,
            error_msg=error_msg,
            action=url_for('op_bp.import_users', demand_id=demand_id)
        )

    return render_template(
        'user/user_import.html',
        form=form,
        action=url_for('op_bp.import_users', demand_id=demand_id)
    )


@op_bp.route('/import/pre_users', methods=['GET', 'POST'])
@login_required
def import_pre_users():
    """
    create by ld_wu 2017-10-24
    导入营销用户
    :return:
    """

    form = ImportUserForm()

    if form.validate_on_submit():
        book = xlrd.open_workbook(file_contents=form.files.data.stream.read())
        sheet = book.sheet_by_index(0)
        mobile_map = dict()
        error_msg = list()
        data_list = list()
        if sheet.ncols != TemplateLength.USER:
            flash('模板错误，请检查导入的excel文件！')
            return redirect(url_for('op_bp.import_pre_users'))
        if sheet.nrows <= MAX_ROW_COUNT:
            for row in range(1, sheet.nrows):
                row_num = row + 1
                schema = ImportUserSchema(sheet, row)
                mobile = schema.mobile = schema.mobile.replace('-', '')
                # 若文件中有重复手机号, 则提示
                if mobile in mobile_map:
                    error_msg.append(
                        (row_num, '该电话工程商在文件已存在, 请检查文件')
                    )
                    continue

                mobile_map[mobile] = row_num

                if schema.error_msg:
                    error_msg.extend(schema.error_msg)
                    continue

                data_list.append(schema)

            users = User.query.filter(
                User.mobile.in_(
                    filter(lambda x: x, mobile_map.keys())
                ),
                User.deleted_at == 0
            )
            existed_users = {user.mobile: user for user in users}
            if error_msg:
                error_msg = sorted(error_msg, key=lambda x: x[0])
            else:
                today = date.today()
                for each in data_list:
                    if each.mobile not in existed_users:
                        para = each.to_dict()
                        city = Area.query.filter(
                            Area.type == AreaType.CITY.value,
                            Area.name.like('%{}%'.format(each.city))
                        ).first()
                        if city:
                            para['city'] = city.name
                            para['area_id'] = city.id
                        if para.get('com'):
                            para['com'] = para['com'][:64]

                        prov = Area.query.filter(
                            Area.type == AreaType.PROV.value,
                            Area.name.like('%{}%'.format(each.prov))
                        ).first()
                        if prov:
                            para['prov'] = prov.name
                        user = User.create(
                            industry=2,
                            wx_openid='',
                            remark='{}导入'.format(today),
                            type=UserType.POTENTIAL.value,
                            level=10,  # 新用户默认为铁牌
                            gender=1,  # 性别默认为男
                            status=0,  # 审核状态默认未认证
                            active=1,  # 默认激活?
                            sms_marketing_obj=True,  # 营销对象
                            credit=0,   # 成就值默认为0
                            **para
                        )
                        # TODO by ld_wu 2018-04-23 写入用户关注的省份
                        UserTag.default_tag(user.id)
                flash('导入成功！')
        else:
            flash(
                '上传数据不可超过{}行，若数据过多请分多次上传！'.format(MAX_ROW_COUNT)
            )
        return render_template(
            'user/user_import.html',
            form=form,
            error_msg=error_msg,
            action=url_for('op_bp.import_pre_users')
        )

    return render_template(
        'user/user_import.html',
        form=form,
        action=url_for('op_bp.import_pre_users')
    )
